//
//  grabSingleView.m
//  AppointmentForCar
//
//  Created by TheMacBook on 2016/11/11.
//  Copyright © 2016年 Herron. All rights reserved.
//

#import "grabSingleView.h"

@implementation GrabSingleView {
    UILabel * _gralSingleLabel;
    UILabel * _countDownLabel;
    NSTimer * _timer;
    NSInteger _interval;
    UIImageView * _backImageView;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if(self) {
        _interval = 20; // 默认20s
        _gralSingleLabel = [[UILabel alloc] init];
        _countDownLabel = [[UILabel alloc] init];
        _backImageView = [[UIImageView alloc] init];
        self.addSubview(_gralSingleLabel).addSubview(_countDownLabel);
        [self insertSubview:_backImageView atIndex:0];
        _gralSingleLabel.backgroundColor = [UIColor clearColor];
        _countDownLabel.backgroundColor = [UIColor clearColor];
        _gralSingleLabel.textAlignment = NSTextAlignmentCenter;
        _countDownLabel.textAlignment = NSTextAlignmentCenter;
        __weak typeof(self) weakSelf = self;
        [_gralSingleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(weakSelf);
            make.top.equalTo(weakSelf.mas_top).mas_offset(kScaleHeight(10));
            make.bottom.equalTo(_countDownLabel.mas_top);
        }];
        [_countDownLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(weakSelf);
            make.height.mas_equalTo(_gralSingleLabel.mas_height);
            make.bottom.equalTo(weakSelf.mas_bottom).mas_offset(-kScaleHeight(5));
        }];
        [_backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(weakSelf);
        }];
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(reduceInterval) userInfo:nil repeats:YES];
        _gralSingleLabel.text = @"抢单";
        _gralSingleLabel.textColor = [UIColor whiteColor];
        _gralSingleLabel.font = kAppFontSize(17);
        _countDownLabel.textColor = [UIColor whiteColor];
        _countDownLabel.text = @"20秒";
    }
    return self;
}

- (void)reduceInterval {
    @synchronized(self)  {
        _interval --;
        _countDownLabel.text = [NSString stringWithFormat:@"%ld秒",(long)_interval];
//        _isStart = YES;
    }
    if(_interval == 0.0f) {
        if (_timer) {
            [_timer invalidate];
            _timer = nil;
        }
        if([_delegate respondsToSelector:@selector(countDownStop)]) {
            [_delegate countDownStop];
        }
    }
}

- (void)setBackImage:(UIImage *)backImage {
    _backImage = backImage;
    _backImageView.image = backImage;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if([_delegate respondsToSelector:@selector(grabSingle:)]) {
        [_delegate grabSingle:self];
    }
}

- (void)removeToWindos {
    [_timer invalidate];
    _timer = nil;
    [self removeFromSuperview];
}

@end
